package com.jueling.culture.controller;


import com.jueling.culture.compent.RedisComponent;
import com.jueling.culture.core.Result;
import com.jueling.culture.core.ResultGenerator;
import com.jueling.culture.dto.res.CaptchaVO;
import com.jueling.culture.exception.FrontShowException;
import com.jueling.culture.util.CaptchaUtil;
import com.jueling.culture.util.RedisKeyGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author linp
 * @date 2020/5/19
 */
@RestController
public class VerificationCodeController {

    @Autowired
    private RedisComponent redisComponent;

    /**
     * 获取验证码图片
     *
     * @return
     */
    @GetMapping("/verification/{key}")
    public Result verification(HttpServletResponse response, @PathVariable String key) {
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        // 禁止图像缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //实例生成验证码对象
        CaptchaUtil instance = new CaptchaUtil();
        //获取验证码
        String code = instance.getCode();
        //将验证码移除，key为时间戳
        redisComponent.remove(RedisKeyGeneratorUtil.genVerificationCodeKey(key));
        //将验证码存至redis，key为时间戳
        String newKey = Long.toString(System.currentTimeMillis());
        redisComponent.set(RedisKeyGeneratorUtil.genVerificationCodeKey(newKey),code,RedisKeyGeneratorUtil.EXPIRED_TIME_300L);
        //将新的key放入头部
        response.setHeader("key",newKey);
        String img = null;
        try {
            img = instance.img2String();
        } catch (IOException e) {
            e.printStackTrace();
        }
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setImg(img);
        captchaVO.setKey(newKey);
        return ResultGenerator.genSuccessResult(captchaVO);

    }

    /**
     * 校验验证码
     * @param code
     * @param key
     * @return
     */
    @GetMapping("/check/verification")
    public Result checkCode(@RequestParam String code, @RequestParam String key) {
        Object oldCode = redisComponent.get(RedisKeyGeneratorUtil.genVerificationCodeKey(key));
        if(oldCode == null){
            throw new FrontShowException("验证码已过期");
        }
        if(!oldCode.toString().equalsIgnoreCase(code)){
            throw new FrontShowException("验证码错误");
        }
        return ResultGenerator.genSuccessResult();
    }
}
